//
//  CZFilesOperatoion.swift
//  shopDemo
//
//  Created by wulanzhou on 2017/7/17.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

import UIKit

class CZFilesOperatoion: NSObject {
    
    static let shared = CZFilesOperatoion()
    private override init() {
        
    }

    public enum FileDirectoryType : Int {
    
        case FileDirectoryDocumentType
        case FileDirectoryCacheType
        case FileDirectoryTempType
    }

    /// 获取文件路径
    ///
    /// - Parameter type: 路径类型
    /// - Returns: 返回路径
    func getFilePathWithType(type:FileDirectoryType) -> String {
        var path:String = ""
        switch type {
        case .FileDirectoryDocumentType:
             path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))[0] as String
        case .FileDirectoryCacheType:
             path = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true))[0] as String
        case .FileDirectoryTempType:
            path = NSTemporaryDirectory()
        }
        
        return path
    }
    
    
    /// 创建目录
    ///
    /// - Parameter path: 目录路径
    /// - Returns: true:成功 false:失败
    func createDirectory(path:String) -> Bool {
        var isDir : ObjCBool = false
        let existed:Bool = FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
        var success:Bool = true
        if (!(isDir.boolValue == true && existed == true) ) {
            
            do{
                //创建目录
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
                print("创建目录成功")
            }catch{
                success = false
                print("创建目录失败")
            }
            
        }
        
        return success
    }
    
    /// 判断文件是否存在
    ///
    /// - Parameter path: 文件路径
    /// - Returns: true:存在 false:不存在
    func isExists(path:String) -> Bool {
        if(path.characters.count > 0){
           return FileManager.default.fileExists(atPath: path)
        }
        return false
    }
    
    /// 删除目录下的所有文件
    ///
    /// - Parameter atPath: 文件路径
    func  removeDirectoryFile(atPath:String) {
        let fileArray:[String]? = FileManager.default.subpaths(atPath: atPath)
        for fn in fileArray!{
            try! FileManager.default.removeItem(atPath: atPath + "/\(fn)")
        }
    }
    
    /// 删除目录
    ///
    /// - Parameter atPath: 文件路径
    func removeDirectory(atPath:String)  {
        try! FileManager.default.removeItem(atPath: atPath)
    }
}
